﻿using Microsoft.Ajax.Utilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.HPSF;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.XPath;
using YunShop_WebAPI.Model;

namespace YunShop_WebAPI.BLL
{
    public class MemberCardService
    {
        public static object OnLogin(string appid, string code, string scene, ref string message, ref int status)
        {

            var appModel = new SystemAppModel();
            string sDbSplit = "";
            //appModel.FHostIP = GetLoginClusterIP(ref sMasterFlag, ref sDbSplit);
            string openid = "";
            string unionid = "";
            int CorpId = 0;
            ArrayList dt = DBHelper.Select(@"select FItemID as CorpId,FStockID,FParentID,FName as StoreName,FAdvUrl       from  t_Corpration where FBusinessKey=@scene", new List<SqlParameter>() { new SqlParameter("@scene", scene) }.ToArray(), DBHelper.ConnMaster);
            if (dt.Count > 0)
            {
                CorpId = CommonFun.ConvertToInt((dt[0] as Hashtable)["CorpId"]);
            }
            else
            {
                status = 0;
                message = "查询不到店铺~";
                return null;
            }


            if (!GetUserInfo(appid, code, ref openid, ref unionid, ref message, CorpId, DBHelper.ConnMaster))
            {
                status = 0;
                message = "code解析失败";
                return null;
            }

            StringBuilder sql = new StringBuilder();
            sql.Append(@"SELECT  [FItemID],[FOpenID],[FCorpID],[FUserID],[FCreateTime],[FLoginTime],[FPhone],[FUnionID],[FNiName],[FGender],[FCity],[FProvince],[FCountry],[FAvatarUrl],[FHostID],[FSettingID],[FStockID],[FMemberID]  FROM [KingCloudShop].[dbo].[t_UserWeixin] where [FUnionID] = @FUnionID and  FCorpID>0  ");
            if (CorpId > 0)
            {
                sql.Append(" and FCorpID = " + CorpId);
            }


            List<SqlParameter> ltpara = new List<SqlParameter>
                        {
                            new SqlParameter("@FUnionID", unionid)
                        };
            ArrayList userWx = DBHelper.Select(sql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster);
            if (userWx.Count is 0)
            {
                return new ArrayList();
            }


            Hashtable userWxInfo = userWx[0] as Hashtable;

            //Dictionary<string, object> userWxInfo = JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(userWxInfoO));
            string m_FPhone = userWxInfo["FPhone"] as string;
            int? m_FUserID = userWxInfo["FUserID"] as int?;
            long? m_FWeixinId = userWxInfo["FItemID"] as long?;
            long? m_FStockID = userWxInfo["FStockID"] as long?;
            long m_CorpId = CommonFun.ConvertToInt(userWxInfo["FCorpID"]);


            Hashtable ht = new Hashtable();

            status = 1;
            message = "登录成功";
            appModel.FCorpID = (int)m_CorpId;
            appModel.FUserID = m_FUserID == null ? 0 : (int)m_FUserID;   // 用户ID
            //appModel.FStockID = FStockID;
            appModel.FOwnerID = 0; //用户组ID
            appModel.FWeixinID = m_FWeixinId.Value;

            string msql = @"SELECT FDbHostIP,FDbSplit,FDbHostNetIP FROM t_CorpHost where FMinCorpID <= {0} and FMaxCorpID >= {0}";
            if (appModel.FParentID > 0)
                msql = string.Format(msql, appModel.FParentID);
            else msql = string.Format(msql, appModel.FCorpID);

            ArrayList dataAll = DBHelper.Select(msql, DBHelper.ConnMaster);
            if (dataAll.Count > 0)
            {
                Hashtable record = (Hashtable)dataAll[0];
                appModel.FHostIP = CommonFun.ConvertToString(record["FDbHostIP"]);
                appModel.FDbSplit = CommonFun.ConvertToString(record["FDbSplit"]);
                if (DBHelper.DebugFlag) appModel.FHostIP = CommonFun.ConvertToString(record["FDbHostNetIP"]);
            }



            /*问题出在这个存储过程*/

            string eptStr = "";
            string m_sql = @"Exec pr_min_GetMemberLogin @FWxAppID,@FUnionID,@FOpenID,@FPhone,@FAvatarUrl,@FNickName,@FStockID";
            SqlParameterList parlist = new SqlParameterList();
            parlist.Add("@FWxAppID", SqlDbType.VarChar, appid);
            parlist.Add("@FUnionID", SqlDbType.VarChar, eptStr);
            parlist.Add("@FOpenID", SqlDbType.VarChar, openid);
            parlist.Add("@FPhone", SqlDbType.VarChar, m_FPhone);
            parlist.Add("@FAvatarUrl", SqlDbType.VarChar, eptStr);
            parlist.Add("@FNickName", SqlDbType.VarChar, m_FPhone);
            parlist.Add("@FStockID", SqlDbType.BigInt, m_FStockID);
            DataSet ds = DBHelper.GetDataSet(m_sql, parlist.Get_List(), DBHelper.ConnMaster);
            //API10.BLL.CLog.Write("pr_min_GetMemberLogin.GetDataSet:" + connstr);
            if ((ds == null) || (ds.Tables.Count < 2))
            {
                message = "缺少参数code";
                return null;
            }
            DataTable dt_user = ds.Tables[0];
            DataTable dt_stock = ds.Tables[1];
            DataTable dt_member = ds.Tables[2];
            //API10.BLL.CLog.Write("pr_min_GetMemberLogin.dt_user:" + secret);
            long m_MemberID = CommonFun.ConvertToBigInt(dt_member.Rows[0]["MemberId"]);
            string sSystemAppID = WxSystemInfo.SetSystemAppID(0, (int)m_CorpId, (long)m_FStockID, (long)m_FWeixinId, m_MemberID, "");

            if ((dt_user.Rows.Count > 0) && (dt_stock.Rows.Count > 0))
            {
                DataRow dr_user = dt_user.Rows[0];
                int mHostId = CommonFun.ConvertToInt(dr_user["FSettingID"]);
                int mCorpId = CommonFun.ConvertToInt(dr_user["FCorpID"]);
                Int64 mStockID = CommonFun.ConvertToBigInt(dr_user["FStockID"]);
                Int64 mMemberID = CommonFun.ConvertToBigInt(dr_user["FMemberID"]);
                Int64 mWeixinID = CommonFun.ConvertToBigInt(dr_user["FItemID"]);
                sSystemAppID = WxSystemInfo.SetSystemAppID(mHostId, (int)mCorpId, (long)mStockID, (long)m_FWeixinId, mMemberID, "");
            }


            Hashtable result = new Hashtable();
            result["status"] = 1;
            result["msg"] = "登录成功";
            result["sessionId"] = "jsedxlcyueqg4mf1y0abgymt";
            result["Token"] = "jsedxlcyueqg4mf1y0abgymt";
            result["mSystemAppID"] = sSystemAppID;
            result["business_key"] = "qG2WCC4B/RxFqQzaI3EMYw==";//b_business_account.business_key
            result["data"] = DBHelper.DataTable2ArrayList(dt_user);
            result["stockdata"] = DBHelper.DataTable2ArrayList(dt_stock);
            result["memberdata"] = DBHelper.DataTable2ArrayList(dt_member);
            status = 1;
            message = "登录成功";
            return result;
        }

        /// <summary>
        /// 小程序用户登录 Chris Lee
        /// </summary>
        public static bool GetUserInfo(string appid, string code,
            ref string openId, ref string unionid, ref string message, int CorpId, string connstr)
        {
            try
            {
                var secret = GetAppSecret(appid);
                if (string.IsNullOrEmpty(secret))
                {
                    message = "secret不能为空";
                    return false;
                }

                //获取openId
                JObject jo = WxService.GetOpenIdByCode(code, appid, secret);
                unionid = CommonFun.GetJObjectValue(jo, "unionid");
                openId = CommonFun.GetJObjectValue(jo, "openid");//orPaa5eBqlpEauuYCjEKPMnxpMa0

                //if (string.IsNullOrEmpty(unionId) && string.IsNullOrEmpty(openId))
                if (string.IsNullOrEmpty(openId))
                {
                    message = "code解析失败";
                    return false;
                }

                // 判断用户是否存在，如果不存在则插入
                string sql = @"SELECT FNiName FROM dbo.t_UserWeixin  where FUnionID=@FUnionID";
                SqlParameterList parlist = new SqlParameterList();
                parlist.Add("@FUnionID", SqlDbType.VarChar, unionid);
                DataTable dt = DBHelper.GetDataTable(sql, parlist.Get_List(), connstr);

                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[index: 0];
                    return true;
                }
                else
                {
                    sql = @"insert into t_UserWeixin(FCreateTime,FNiName,FCorpID,FUnionID) values(@FCreateTime,0,@CorpId,@FUnionID)";
                    //@FUnionID,@FNiName,@FAvatarUrl,
                    SqlParameterList par_list = new SqlParameterList();
                    //par_list.Add("@FOpenID", SqlDbType.VarChar, openId);
                    par_list.Add("@FUnionID", SqlDbType.VarChar, unionid);
                    par_list.Add("@FCreateTime", SqlDbType.DateTime2, DateTime.Now);
                    //par_list.Add("@FUnionID", SqlDbType.VarChar, unionId);
                    par_list.Add("@FNiName", SqlDbType.VarChar, "李");
                    par_list.Add("@CorpId", SqlDbType.Int, CorpId > 0 ? CorpId : 52);
                    //par_list.Add("@FAvatarUrl", SqlDbType.VarChar, openId);
                    string msg = DBHelper.ExeSQL(sql, par_list.Get_List(), connstr);
                    return true;
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return false;
            }

        }
        /// <summary>
        /// 通过appid获取密钥
        /// </summary>
        /// <param name="appid"></param>
        /// <returns></returns>
        public static string GetAppSecret(string appid)
        {
            string sql = @"select FAppSecret from t_MiniSetting where FAppID=@FAppID";
            SqlParameterList parlist = new SqlParameterList();
            parlist.Add("@FAppID", SqlDbType.VarChar, appid);
            DataTable dt = DBHelper.GetDataTable(sql, parlist.Get_List(), DBHelper.ConnMaster);

            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                return CommonFun.ConvertToString(dr["FAppSecret"]);
            }
            return "";
        }

        public static List<MemberDataResponse> GetMemberData(string sSystemAppID)
        {
            int mCorpID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.CorpID);
            int mMemberID = WxSystemInfo.GetSystemAppID(sSystemAppID, WxSystemAppID.MemberID);
            var data = GetMemberDataByID(mMemberID, mCorpID, sSystemAppID);
            return data;
        }

        /// <summary>
        /// 获取会员信息
        /// </summary>
        /// <returns></returns>
        public static List<MemberDataResponse> GetMemberDataByID(Int64 mMemberID, int mCorpID, string shop_appid)
        {
            try
            {
                string connstr = SystemInfo.GetClusterConn(shop_appid);
                var sql = @"Exec pr_min_GetMemberData @FMemberID,@FCorpID";
                SqlParameterList parlist = new SqlParameterList();
                parlist.Add("@FMemberID", SqlDbType.BigInt, mMemberID);
                parlist.Add("@FCorpID", SqlDbType.Int, mCorpID);
                ArrayList dt = DBHelper.Select(sql, parlist.Get_List(), DBHelper.ConnMaster);
                return JsonConvert.DeserializeObject<List<MemberDataResponse>>(JsonConvert.SerializeObject(dt));
            }
            catch (Exception e)
            {
                return null;
            }
        }

        public static Hashtable SystemParam(string hostid, string corpid)
        {

            int iCorpId = CommonFun.ConvertToInt(corpid);
            var sql = @"select FMiniProgramName,FMiniBGK from t_SystemPara where FCorpID=@FItemID";

            var data = DBHelper.Select(sql, new List<SqlParameter>() {
            new SqlParameter("@FItemID",corpid)
            }.ToArray(), DBHelper.ConnMaster)[0] as Hashtable;
            var jo = new Hashtable();
            if (data != null)
            {
                jo.Add("FMiniProgramName", data["FMiniProgramName"]);
                var url = (string)data["FMiniBGK"];
                if (url.IndexOf("..") >= 0)
                {
                    url = url.Substring(url.IndexOf("..") + 2);
                }
                if (!string.IsNullOrEmpty(url))
                    url = "http://erp.posyun3721.com" + url;//.Replace("../", "");
                jo.Add("FMiniBGK", url);
            }
            return jo;
        }

        public static List<t_MemberDepositGive> DepositGiveData(int corpId, int memberId, string sSystemAppID, int mDatatype = 0, string amount = "0")
        {



            var sql = @"select FItemID,FAmount,FGiveAmt,FGivePoint
                        from t_MemberDepositGive
                        where FCorpID=@FCorpID and FState = 1 and FDeleted = 1 and FDataType=@FDatatype 
                        and GETDATE() between FBeginTime and FEndTime 
                        and (FClassID=0 or FClassID in (select FClassID from t_Member where FItemID=@FItemID)) ";

            if (mDatatype == 1)
            {//次卡
                sql = @"select top 1 FItemID,FAmount,
                            case when isnull(FAddingFlag,0)>0 then isnull(FGiveAmt,0)*(@FAmount/FAmount) else isnull(FGiveAmt,0) end  as FGiveAmt,FGivePoint
                            from t_MemberDepositGive
                            where FCorpID=@FCorpID and FState = 1 and FDeleted = 1 and FDataType=@FDatatype 
                            and GETDATE() between FBeginTime and FEndTime 
                            and (FClassID=0 or FClassID in (select FClassID from t_Member where FItemID=@FItemID)) 
                            and FAmount<=@FAmount
                            order by case when isnull(FAddingFlag,0)>0 then isnull(FGiveAmt,0)*(@FAmount/FAmount) else isnull(FGiveAmt,0) end desc";
            }
            ArrayList result = DBHelper.Select(sql, new List<SqlParameter>() {
                        new SqlParameter("@FCorpID",corpId),
                        new SqlParameter("@FItemID",memberId),
                        new SqlParameter("@FDatatype",mDatatype),
                        new SqlParameter("@FAmount",amount),
            }.ToArray(), DBHelper.ConnMaster);


            return JsonConvert.DeserializeObject<List<t_MemberDepositGive>>(JsonConvert.SerializeObject(result));
        }

        public static List<MemberDepositResponse> GetMemberDeposit(long memberId, int mDataType, string mDateStar, string mDateEnd, int pageIndex, int pageSize, string sSystemAppID)
        {
            int corpId = 0;

            string sql = "SELECT * FROM t_MemberDeposit where  FCorpID= @mCorpID  and FMemberID = @mMemberID   and FDataType= @mDataType ";
            List<SqlParameter> sqlParameters = new List<SqlParameter>() {
                        new SqlParameter("@mPageSize",pageSize),
                        new SqlParameter("@mPageIndex",pageIndex),
                        new SqlParameter("@mCorpID",corpId),
                        new SqlParameter("@mMemberID",memberId),
                        new SqlParameter("@mDataType",mDataType),
            };
            if (mDateStar != null)
            {
                sql += " and FDate>= @mDate1 and FDate<= @mDate2 ";
                sqlParameters.Add(new SqlParameter("@mDate1", mDateStar));
                sqlParameters.Add(new SqlParameter("@mDate2", mDateEnd));
            }

            /*        var result = DB.Query<MemberDepositResponse>(connstr, sql, new
                    {
                        mPageSize = iPageSize,
                        mPageIndex = iPageIndex,
                        mCorpID = 0,
                        mMemberID = iMemberId,
                        mDate1 = mDateStar,
                        mDate2 = mDateEnd,
                        mDataType = sDataType
                    }).ToList();*/

            ArrayList result = DBHelper.Select(sql, sqlParameters.ToArray(), DBHelper.ConnMaster);

            return JsonConvert.DeserializeObject<List<MemberDepositResponse>>(JsonConvert.SerializeObject(result));
        }


        /// <summary>
        /// 获取次卡方案
        /// </summary>
        /// <param name="corpId"></param>
        /// <returns></returns>
        public static List<MemberTimeResponse> GetMemberTime(int stockId, int corpId, string shop_appid)
        {
            string connstr = SystemInfo.GetClusterConn(shop_appid);//
            List<MemberTimeResponse> data;
            string sql = @"SELECT a.*, 0 AS FSetQty,s.FName AS StockName FROM dbo.t_MemberTime AS a INNER JOIN
                        dbo.t_Stock AS s ON a.FStockID = s.FItemID where (a.FCorpID = @FCorpID) AND (a.FDeleted = 1) 
                        AND (a.FState = 0) AND (GETDATE() BETWEEN a.FStartDate AND a.FEndDate)";
            List<SqlParameter> sqlParameters = new List<SqlParameter>() {
                        new SqlParameter("@FCorpID",corpId),
            };
            ArrayList result = DBHelper.Select(sql, sqlParameters.ToArray(), DBHelper.ConnMaster);
            data = JsonConvert.DeserializeObject<List<MemberTimeResponse>>(JsonConvert.SerializeObject(result));

            if (data != null && data.Count > 0)
            {
                data.ForEach(r =>
                {
                    switch (r.FCardType)
                    {
                        case 0:
                            r.FCardTypeDesc = "不限制天数";
                            break;
                        case 1:
                            r.FCardTypeDesc = string.Format("自购买之日起{0}天内有效", r.FEffectDays.ToString());
                            break;
                        case 2:
                            r.FCardTypeDesc = string.Format("{0} {1}"
                                , new[] { r.FStartDate.ToString("yyyy-MM-dd"), r.FEndDate.ToString("yyyy-MM-dd") });
                            break;
                    }
                });
            }

            return data;
        }

        public static ArrayList GetMemberPoint(string hostId, string memberId, string pageIndex, string pageSize, string sSystemAppID)
        {
            var iPageIndex = Convert.ToInt32(pageIndex);
            var iPageSize = Convert.ToInt32(pageSize);
            long iMemberId = Convert.ToInt64(memberId);

            string connstr = DBHelper.ConnMaster;//
            var sql = GetSelectPageSQL(
                "a.FEntryID", "a.FEntryID, a.FBillNo, a.FCorpID, a.FStockID, b.FName AS StockName, "
                 + "a.FUserID, a.FDataType, a.FDate, a.FPoint, a.FSetPoint, a.FRemark",
                @" FROM dbo.t_MemberDpPoint AS a with(NOLOCK) INNER JOIN
                      dbo.t_Stock AS b with(NOLOCK) ON a.FStockID = b.FItemID where a.FMemberID=@FMemberID ", false);

            ArrayList result = DBHelper.Select(sql, new List<SqlParameter>()
            {
            new SqlParameter("@PageIndex",pageIndex),
            new SqlParameter("@PageSize",pageSize),
            new SqlParameter("@FMemberID",memberId),
            }.ToArray(), connstr);
            return result;
        }

        /// <summary>
        /// 表值自动分页查询，必须有主键sPrimary
        /// </summary>
        /// <param name="sPrimary">主键</param>
        /// <param name="sFieldList">查询的字段集合</param>
        /// <param name="sql">查询的表关联集合</param>
        /// <returns></returns>
        public static string GetSelectPageSQL(string sPrimary, string sFieldList, string sql, bool bAsc = true)
        {
            /*
              string sPrimary = " a.FItemID ";
                string sFieldList = @" a.FItemID,a.FParentID,a.FNumber,a.FName,a.FIcon,a.FRemark,isnull(b.FName,'系统') as FCorpName ";
                string sql = @"  from t_GoodsClass a left outer join t_corpration b on b.FItemID=a.FCorpID 
                                        Where (a.FDeleted > 0) and (a.FCorpID = @mCorpID or a.FCorpID=0)";
             */

            var sOrderBy = bAsc ? "asc" : "desc";

            //@PageSize每页多少条记录
            //@PageIndex指定当前为第几页
            string msql = string.Format(@"Declare @RowCount int 
                    Declare @StartRecord int
                    Declare @EndRecord int 
                    Declare @mPageIndex int 
                    Declare @mPageSize int 
                    
                    select @mPageSize=@PageSize,@mPageIndex=@PageIndex
                    if (@mPageSize = 0) Set @mPageSize = 2
                    set @StartRecord = (@mPageIndex - 1) * @PageSize + 1 
                    set @EndRecord = @mPageIndex * @PageSize
                    Select @RowCount=Count({0}) {2}
                    select *,@RowCount as FRowCount from (select row_number() over (order by {0} {3}) as FRowId,
                    {1} {2}) as t where FRowId between @StartRecord and @EndRecord+1", sPrimary, sFieldList, sql, sOrderBy);

            //string sOrderBy = string.Format("order by {0} {1}", sPrimary, bAsc ? " asc " : " desc ");
            //msql += sOrderBy;
            return msql;
        }

        public static bool UpdateMemberData(long memberId, string phone, int corpID, string name, int sex, string birthday, string email, string address)
        {

            var result = false;
            try
            {
                string connstr = DBHelper.ConnMaster;//
                var sql = @"update t_Member set FName=@mName where FItemId=@mMemberId and FDeleted=1;
                            update t_MemberDetail set FSex=@mSex,FBirthday=@mBirthday,FEMail=@mEMail,FAddress=@mAddress where FItemId=@mMemberId ";

                if (birthday == null || birthday == "")
                    sql = sql.Replace("@mBirthday", "null");
                DBHelper.ExeSQL(sql, new List<SqlParameter>() {
                        new SqlParameter("@mMemberId",memberId),
                        new SqlParameter("@mSex",sex),
                        new SqlParameter("@mName",name),
                        new SqlParameter("@mBirthday",birthday),
                        new SqlParameter("@mEMail",email),
                        new SqlParameter("@mAddress",address),
                }.ToArray(), connstr);
                return true;
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
                result = false;
            }
            return result;
        }



        /// <summary>  
        /// 获取时间戳  
        /// </summary>  
        /// <returns></returns>  
        public static Int64 GetTimeStampMS()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.Milliseconds);
        }

        public static string GetMobilePayClientSn(string sBillNo)
        {
            string mBillNo = sBillNo + "-" + GetTimeStampMS();

            if (mBillNo.Length > 32)
            {
                mBillNo = mBillNo.Substring(mBillNo.Length - 32);
            }

            return mBillNo;
        }

        /// <summary>
        /// 定时轮询查单ArrayList rows, int FCorpID, int FUserID,decimal Money,ref string msg
        /// </summary>
        public static void SetRepeatQueryPay(ArrayList rows, string order_no, int business_id, int FYears, int type, string shop_appid)
        {
            //支付的订单类型，1：商城订单，1：从订单列表来的商城订单,11：会员充值
            Thread newThread = new Thread(() =>
            SetRepeatQueryPay_Thread(rows, order_no, business_id, FYears, type, shop_appid), 1024 * 512);
            newThread.Name = String.Format("Thread{0}", order_no);
            newThread.Start();
        }
        /// <summary>
        /// 定时轮询查单
        /// </summary>
        public static void SetRepeatQueryPay_Thread(ArrayList rows, string order_no, int business_id, int FYears, int type, string shop_appid)
        {
            bool bLoop = true;
            int mSleepTime = 10000;
            int mTimCount = 0;
            try
            {
                Thread.Sleep(mSleepTime);
                while (bLoop)
                {
                    Hashtable respData = new Hashtable();
                    bool bResult = SxfPayCommon.Query(order_no, business_id, ref respData);
                    if (bResult)
                    {
                        //  支付成功
                        string m_sql = @"select * from y_Mall_PayOrder where FBillNo= @FBillNo";
                        List<SqlParameter> m_params = new List<SqlParameter>() {
                        new SqlParameter("@FBillNo",order_no)
                        };
                        ArrayList m_PayOrders = DBHelper.Select(m_sql, m_params.ToArray(), DBHelper.ConnMaster);
                        //SystemInfo.writeServiceLog("m_PayOrders", JsonConvert.SerializeObject(m_PayOrders), "11", "AA", DBHelper.ConnMaster);
                        if (m_PayOrders.Count > 0)
                        {
                            Hashtable m_Pay_Order = m_PayOrders[0] as Hashtable;
                            long m_MInterID = CommonFun.ConvertToBigInt(m_Pay_Order["MInterID"]);

                            DateTime.TryParseExact(CommonFun.ConvertToString(respData["payTime"]), "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime m_PayTime);
                            m_sql = @"UPDATE [dbo].[y_Mall_PayOrder] SET  [FPayTime] = @FPayTime, [FPayState] = 1 where [FBillNo]= @FBillNo ";
                            m_params = new List<SqlParameter>() {
                                    new SqlParameter("@FPayTime",m_PayTime),
                                    new SqlParameter("@FBillNo",order_no),
                                    };
                            DBHelper.ExeSQL(m_sql, m_params.ToArray(), DBHelper.ConnMaster);
                            //SystemInfo.writeServiceLog(" UPDATE y_Mall_PayOrder", JsonConvert.SerializeObject(respData), "22", "BB", DBHelper.ConnMaster);
                            m_sql = @"UPDATE [dbo].[y_Mall_Master] SET [FStateID] = 1,[FPayDate]=@FPayDate,[FPayFlag] = 1,[FPayType] = 1 where [KInterID]= @KInterID ";
                            m_params = new List<SqlParameter>() {
                                    new SqlParameter("@KInterID",m_MInterID),
                                    new SqlParameter("@FPayDate",m_PayTime),
                                    };
                            DBHelper.ExeSQL(m_sql, m_params.ToArray(), DBHelper.ConnMaster);
                            //SystemInfo.writeServiceLog("UPDATE y_Mall_Master", JsonConvert.SerializeObject(m_PayOrders), "33", "CC", DBHelper.ConnMaster);
                        }

                    }
                    if (mTimCount > 12) bLoop = false;
                    mTimCount += 1;
                    Thread.Sleep(mSleepTime);
                }
            }
            catch (Exception err)
            {

            }
        }


        public static bool PaySMS(string shop_appid, string BillNo, string payID)
        {
            try
            {
                int mCorpID = SystemInfo.GetSystemAppID(shop_appid, SystemAppID.CorpID);
                string connstr = SystemInfo.GetClusterConn(shop_appid);
                string sql = @"exec pr_bi_RechargeSMS @FBillNo,@FPayID";
                SqlParameterList par_list = new SqlParameterList();
                par_list.Add("@FBillNo", SqlDbType.VarChar, BillNo);
                par_list.Add("@FPayID", SqlDbType.VarChar, payID);
                DataTable dt = DBHelper.GetDataTable(sql, par_list.Get_List(), connstr);

                if (dt == null)
                    return false;
                if (dt.Rows.Count == 0)
                    return false;
                if (CommonFun.ConvertToInt(dt.Rows[0]["retvalue"]) > 0)
                    return true;
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                return false;
            }
        }

        public static List<MemberTimeResponse> MemberTimeList(int corpID, int stockID, long memberId)
        {
            string connstr = DBHelper.ConnMaster;//

            var corpData = GetStockById(stockID).FirstOrDefault();
            List<MemberTimeResponse> memberTimeList = GetMemberTimeByCorpId(corpID);
            var list = new List<MemberTimeResponse>();
            ArrayList array = DBHelper.Select("pr_bi_GetMemberTimeInv @stockId,@memberId,1", new List<SqlParameter>() { new SqlParameter("@stockId", stockID), new SqlParameter("@memberId", memberId) }.ToArray(), connstr);
            List<dynamic> data = JsonConvert.DeserializeObject<List<dynamic>>(JsonConvert.SerializeObject(array));
            /*     var data = DB.QueryProcTrans<dynamic>(connstr, "pr_bi_GetMemberTimeInv",
                     new { FStockID = stockID, FMemberID = memberId, FDataType = 1 }).ToList();*/
            if (data != null && data.Count > 0)
            {
                data.ForEach(r =>
                {
                    var item = (from d in memberTimeList where d.FItemID == r.FMemberTimeID select d).FirstOrDefault();
                    var itemtime = new MemberTimeResponse();
                    if (item != null)
                    {
                        itemtime = item.Copy();
                        itemtime.TotalId = r.TotalId;
                        itemtime.LiveTime = r.FQty;
                        itemtime.FStartDate = r.FStartDate;
                        itemtime.FEndDate = r.FEndDate;
                        itemtime.FDate = r.FDate;
                        itemtime.StatusDesc = "可使用";
                        list.Add(itemtime);
                    }
                });
            }

            ArrayList dataOutTimearray = DBHelper.Select("pr_bi_GetMemberTimeInv @stockId,@memberId,-1", new List<SqlParameter>() { new SqlParameter("@stockId", stockID), new SqlParameter("@memberId", memberId) }.ToArray(), connstr);

            List<dynamic> dataOutTime = JsonConvert.DeserializeObject<List<dynamic>>(JsonConvert.SerializeObject(array));

            if (dataOutTime != null && dataOutTime.Count > 0)
            {
                dataOutTime.ForEach(r =>
                {
                    var item = (from d in memberTimeList where d.FItemID == r.FMemberTimeID select d).FirstOrDefault();
                    var itemtime = new MemberTimeResponse();
                    if (item != null)
                    {
                        itemtime = item.Copy();
                        itemtime.TotalId = r.TotalId;
                        itemtime.LiveTime = r.FQty;
                        itemtime.FStartDate = r.FStartDate;
                        itemtime.FEndDate = r.FEndDate;
                        itemtime.FDate = r.FDate;
                        itemtime.StatusDesc = "已过期";
                    }
                    list.Add(itemtime);
                });
            }

            return list;
        }


        /// <summary>
        /// 获取次卡方案
        /// </summary>
        /// <param name="corpId"></param>
        /// <returns></returns>
        public static List<MemberTimeResponse> GetMemberTimeByCorpId(int corpId)
        {
            var iCorpId = corpId;
            List<MemberTimeResponse> data = null;
            if (iCorpId < 0)
            {
                ArrayList arr = DBHelper.Select("select * from t_MemberTime where FDeleted=1 ", DBHelper.ConnMaster);
                data = JsonConvert.DeserializeObject<List<MemberTimeResponse>>(JsonConvert.SerializeObject(arr));
            }
            else
            {
                ArrayList arr = DBHelper.Select(@"if exists(select FItemID from t_MemberGroupDetail where FSubCorpID=@FCorpID and FDeleted>0)
                            select a.* from t_MemberTime a join (select b.FSubCorpID from t_MemberGroupDetail a 
                            join t_MemberGroupDetail b on a.FGroupID=b.FGroupID where a.FDeleted>0 and b.FDeleted>0 and a.FCorpID=@FCorpID group by b.FSubCorpID) b 
                            on a.FCorpID=b.FSubCorpID where a.FDeleted>0 
                        else
                            select * from t_MemberTime where FCorpID=@FCorpID and FDeleted>0 ",
        new List<SqlParameter>() { new SqlParameter("@FCorpID", corpId) }.ToArray(), DBHelper.ConnMaster);
                data = JsonConvert.DeserializeObject<List<MemberTimeResponse>>(JsonConvert.SerializeObject(arr));
            }

            if (data != null && data.Count > 0)
            {
                data.ForEach(r =>
                {
                    switch (r.FCardType)
                    {
                        case 0:
                            r.FCardTypeDesc = "不限制天数";
                            break;
                        case 1:
                            r.FCardTypeDesc = string.Format("自购买之日起{0}天内有效", r.FEffectDays.ToString());
                            break;
                        case 2:
                            r.FCardTypeDesc = string.Format("{0} {1}"
                                , new[] { r.FStartDate.ToString("yyyy-MM-dd"), r.FEndDate.ToString("yyyy-MM-dd") });
                            break;
                    }
                });
            }

            //设置门店名
            var sql = "select FItemID,FName from t_stock where FDeleted=1";
            var dt = JsonConvert.DeserializeObject<List<dynamic>>(JsonConvert.SerializeObject(DBHelper.Select(sql, DBHelper.ConnMaster)));
            var stock = dt.ToDictionary(r => (long)r.FItemID, v => (string)v.FName);
            data.ForEach(r => r.StockName = (from d in stock where d.Key == r.FStockID select d.Value).FirstOrDefault());

            return data;
        }


        /// <summary>
        /// 根据id获取门店 
        /// </summary>
        /// <param name="stockId"></param>
        /// <returns></returns>
        public static List<StockModel> GetStockById(int stockId)
        {
            string sql = @"select a.*,c.FName as FCorpName from t_Stock a inner join t_Corpration c on a.FCorpID = c.FItemID where a.FItemID = @FItemID";
            ArrayList arr = DBHelper.Select(sql,
                new List<SqlParameter>() { new SqlParameter("@FItemID", stockId) }.ToArray(), DBHelper.ConnMaster);
            return JsonConvert.DeserializeObject<List<StockModel>>(JsonConvert.SerializeObject(arr));

        }

        public static List<MemberTimeStockResponse> GetMemberTimeStock(long mEntryID)
        {
            string connstr = DBHelper.ConnMaster;//
            string msql = @"SELECT a.FEntryID, b.FNumber, b.FName, a.FQty, a.FPrice, 
                    CONVERT(varchar(10),c.FStartDate,120) as FStartDate, 
                    CONVERT(varchar(10),c.FEndDate,120) as FEndDate, a.FMemberTimeID, 
                    CONVERT(varchar(10),c.FDate,120) as FDate, d.FName AS FStockName,
                    case b.FCardType when 0 then '不限' else CONVERT(varchar(10),c.FEndDate,120) end as FStatusDesc
                    FROM dbo.t_MemberTimeTotal AS a INNER JOIN
                      dbo.t_MemberTime AS b ON a.FMemberTimeID = b.FItemID INNER JOIN
                      dbo.t_MemberTimeDetail AS c ON a.FDetailID = c.FDetailID INNER JOIN
                      dbo.t_Stock AS d ON a.FStockID = d.FItemID
                    WHERE (a.FEntryID = {0})";

            msql = string.Format(msql, mEntryID);
            return JsonConvert.DeserializeObject<List<MemberTimeStockResponse>>(JsonConvert.SerializeObject(DBHelper.Select(msql, connstr)));

        }



        public static int GetGoodsListCount(int mCorpID, int mClassID, int mBrandID, string mConditon, int mOrderType)
        {
            int count = 0;
            StringBuilder sb = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();

            sb.Append("select count(a.FItemID) as count  FROM dbo.t_GoodsMall AS m INNER JOIN         dbo.t_Goods AS a ON m.FGoodsID = a.FItemID INNER JOIN t_GoodsDetail b on a.FItemID = b.FItemID         where a.FDeleted = 1 and m.FMallFlag = 1 and m.FCorpID =@mCorpID ");
            ltpara.Add(new SqlParameter("@mCorpID", mCorpID));
            if (mClassID > 0)
            {
                sb.Append(" and a.FClassID in (select FItemID from dbo.f_GetSonNode( @mClassID ))");
                ltpara.Add(new SqlParameter("@mClassID", mClassID));
            }
            if (@mConditon != "")
            {
                string condition = "%" + mConditon + "%";

                // 现在我们可以安全地添加一个带有正确参数的SQL片段  
                sb.Append(" and a.FName like @mConditonWithWildcard");
                // 注意我们创建了一个新的参数名，因为它包含了通配符  
                ltpara.Add(new SqlParameter("@mConditonWithWildcard", condition));
            }

            Hashtable res = DBHelper.Select(sb.ToString(), ltpara.ToArray(), DBHelper.ConnMaster)[0] as Hashtable;
            count = (int)res["count"];

            return count;
        }
        /// <summary>
        /// 商品详情
        /// </summary>
        public static Hashtable GetGoodsDetail(string shop_appid, Int64 goods_id)
        {
            int mCorpID = WxSystemInfo.GetSystemAppID(shop_appid, WxSystemAppID.CorpID);

            //string msql = @"EXEC pr_wap_dh_GetGoodsDetail @mCorpID,@mUserID,@mGoodsID";
            string msql = @"EXEC pr_wap_GetGoodDetail @mCorpID,@FItemID";
            SqlParameterList par_list = new SqlParameterList();
            par_list.Add("@mCorpID", SqlDbType.BigInt, mCorpID);
            //par_list.Add("@mUserID", SqlDbType.BigInt, mUserID);
            par_list.Add("@FItemID", SqlDbType.BigInt, goods_id);
            ArrayList datalist = DBHelper.Select(msql, par_list.Get_List(), DBHelper.ConnMaster);
            Hashtable ht_result = new Hashtable();
            if (datalist != null && datalist.Count > 0)
            {
                ht_result = datalist[0] as Hashtable;
                var itemUrl = CommonFun.ConvertToString(ht_result["FProImage"]);
                ArrayList list_img = new ArrayList();
                if (!string.IsNullOrWhiteSpace(itemUrl))
                {
                    var arr = itemUrl.Replace("$$", "$").Split('$');
                    foreach (var str in arr)
                    {
                        if (!string.IsNullOrWhiteSpace(str))
                        {
                            Hashtable ht_img = new Hashtable();
                            ht_img["FGoodImg"] = str;
                            list_img.Add(ht_img);
                        }
                    }
                }
                ht_result["FProImage"] = list_img;
            }
            return ht_result;
        }

        /// <summary>
        /// 商品详情
        /// </summary>
        public static Hashtable GetGoodsDetail(int mCorpID, Int64 goods_id)
        {
            //string msql = @"EXEC pr_wap_dh_GetGoodsDetail @mCorpID,@mUserID,@mGoodsID";
            string msql = @"EXEC pr_wap_GetGoodDetail @mCorpID,@FItemID";
            SqlParameterList par_list = new SqlParameterList();
            par_list.Add("@mCorpID", SqlDbType.BigInt, mCorpID);
            //par_list.Add("@mUserID", SqlDbType.BigInt, mUserID);
            par_list.Add("@FItemID", SqlDbType.BigInt, goods_id);
            ArrayList datalist = DBHelper.Select(msql, par_list.Get_List(), DBHelper.ConnMaster);
            Hashtable ht_result = new Hashtable();
            if (datalist != null && datalist.Count > 0)
            {
                ht_result = datalist[0] as Hashtable;
                var itemUrl = CommonFun.ConvertToString(ht_result["FProImage"]);
                ArrayList list_img = new ArrayList();
                if (!string.IsNullOrWhiteSpace(itemUrl))
                {
                    var arr = itemUrl.Replace("$$", "$").Split('$');
                    foreach (var str in arr)
                    {
                        if (!string.IsNullOrWhiteSpace(str))
                        {
                            Hashtable ht_img = new Hashtable();
                            ht_img["FGoodImg"] = str;
                            list_img.Add(ht_img);
                        }
                    }
                }
                ht_result["FProImage"] = list_img;
            }
            return ht_result;
        }



        public static bool GenOrder(y_Mall_Shopping _model, long FWeixinID, long CorpID, ref long KInterID, int point)
        {

            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltpara = new List<SqlParameter>();
            List<object> SqlArray = new List<object>();
            List<object> ParaArray = new List<object>();
            string m_zero = "0";
            string m_ept_str = "";
            long agencyCorpId = CorpID;
            decimal li_RealMoney = 0;
            long m_good_id = _model.FGoodsID;
            //取默认仓库
            ltpara = new List<SqlParameter>();
            strSql.Append(@"select FStockID from t_Corpration where FItemID = @FCorpID");
            ltpara.Add(new SqlParameter("@FCorpID", CorpID));
            string stockId = DBHelper.GetDataTable(strSql.ToString(), ltpara.ToArray(), DBHelper.ConnMaster).Rows[0]["FStockID"].ToString();
            //获取购物车数据
            decimal realMoney = 0;
            //应收金额
            decimal li_TotalMoney = 0;
            // 获取商品信息
            //Hashtable goodDetail = GetGoodsDetail((int)CorpID, m_good_id);


            // 插入商城表
            //商城订单主表
            strSql = new StringBuilder();
            ltpara = new List<SqlParameter>();
            // string ls_CreDate = BaseFactory.DbUtils().GetDate();
            string ls_CreDate = Convert.ToDateTime(DBHelper.GetValue("SELECT GETDATE();", DBHelper.ConnMaster)).ToString("yyyy-MM-dd HH:mm:ss");
            KInterID = GetMaxAutoID("y_Mall_Master", "KInterID");
            strSql.Append(@"INSERT INTO y_Mall_Master (KInterID,FBillNo,FDate,FWeixinID,FCorpID,FAmount,FRealAmount,FTelephone,FAddress,FConsignee,FMessage,FStateID,FShippingID,FShippingAmt,FDataType,FValidFlag,FBillFlag,FBillType,FPiece,FPayType,FOrderCorpID,FStockID,FPrvID,FCityID,FAreaID,FCouponAmt,FPayDate,FPayFlag,FPaymentID,FQty)
                  values (@KInterID,@FBillNo,@FDate,@FWeixinID,@FCorpID,@FAmount,@FRealAmount,@FTelephone,@FAddress,@FConsignee,
                  @FMessage,1,@FShippingID,@FShippingAmt,5,1,@FBillFlag,@FBillType,@FPiece,1,@FOrderCorpID,@FStockID,@FPrvID,@FCityID,@FAreaID,@FCouponAmt,@FPayDate,1,1,1)");

            DateTime now = DateTime.Now;
            ltpara.Add(new SqlParameter("@KInterID", KInterID));
            ltpara.Add(new SqlParameter("@FBillNo", $"{now.Year.ToString().Substring(2)}{now.Month}{now.Day}{now.Hour}{now.Minute}{KInterID + 666}"));
            ltpara.Add(new SqlParameter("@FDate", ls_CreDate));
            ltpara.Add(new SqlParameter("@FPayDate", ls_CreDate));
            ltpara.Add(new SqlParameter("@FWeixinID", FWeixinID));
            ltpara.Add(new SqlParameter("@FCorpID", agencyCorpId));
            ltpara.Add(new SqlParameter("@FAmount", li_TotalMoney));
            ltpara.Add(new SqlParameter("@FRealAmount", li_RealMoney));
            ltpara.Add(new SqlParameter("@FTelephone", _model.FTelephone));
            ltpara.Add(new SqlParameter("@FAddress", _model.FAddress));
            ltpara.Add(new SqlParameter("@FConsignee", _model.FConsignee));
            ltpara.Add(new SqlParameter("@FMessage", _model.FMessage));
            ltpara.Add(new SqlParameter("@FShippingID", _model.FShippingID));
            ltpara.Add(new SqlParameter("@FShippingAmt", _model.FShippingAmt));
            ltpara.Add(new SqlParameter("@FBillFlag", _model.FBillFlag));
            ltpara.Add(new SqlParameter("@FBillType", _model.FImportsFlag));
            ltpara.Add(new SqlParameter("@FPiece", _model.FQty));
            ltpara.Add(new SqlParameter("@FOrderCorpID", CorpID));
            ltpara.Add(new SqlParameter("@FStockID", stockId));
            decimal value = Convert.ToDecimal(_model.FCouponMoney);
            ltpara.Add(new SqlParameter("@FCouponAmt", value));
            ltpara.Add(new SqlParameter("@FPrvID", _model.FPrvID));
            ltpara.Add(new SqlParameter("@FCityID", _model.FCityID));
            ltpara.Add(new SqlParameter("@FAreaID", _model.FAreaID));

            SqlArray.Add(strSql);
            ParaArray.Add(ltpara.ToArray());

            // 谢写入商城订单详情表
            int li_mEntryNo = 1;

            strSql = new StringBuilder();
            ltpara = new List<SqlParameter>();
            string mFLargessFlag = "0";

            strSql.Append(@"INSERT INTO y_Mall_Detail (MInterID,mEntryNo,mFGoodID,mFSubItemID,mFConvert,mFQty,mFPrice,
                      mFActualPrice,mFDiscount,mFAmount,mFRealAmount,mFCostPrice,mFQtySend,mFLargessFlag) 
                      values (@MInterID,@mEntryNo,@mFGoodID,@mFSubItemID,@mFConvert,1,@mFPrice,@mFActualPrice,@mFDiscount,
                      @mFAmount,@mFRealAmount,@mFCostPrice,@mFQtySend,@mFLargessFlag)");
            ltpara.Add(new SqlParameter("@MInterID", KInterID));
            ltpara.Add(new SqlParameter("@mEntryNo", li_mEntryNo));
            ltpara.Add(new SqlParameter("@mFGoodID", m_good_id));
            ltpara.Add(new SqlParameter("@mFSubItemID", m_zero));
            ltpara.Add(new SqlParameter("@mFConvert", m_zero));
            //ltpara.Add(new SqlParameter("@mFQty", 1));
            ltpara.Add(new SqlParameter("@mFPrice", m_zero));
            ltpara.Add(new SqlParameter("@mFActualPrice", m_zero));
            ltpara.Add(new SqlParameter("@mFDiscount", m_zero));
            ltpara.Add(new SqlParameter("@mFAmount", m_zero));
            ltpara.Add(new SqlParameter("@mFRealAmount", m_zero));
            ltpara.Add(new SqlParameter("@mFCostPrice", m_zero));
            ltpara.Add(new SqlParameter("@mFQtySend", _model.FQty));
            ltpara.Add(new SqlParameter("@mFLargessFlag", mFLargessFlag));
            li_mEntryNo++;
            SqlArray.Add(strSql);
            ParaArray.Add(ltpara.ToArray());

            //商城订单付款表
            strSql = new StringBuilder();
            ltpara = new List<SqlParameter>();
            strSql.Append(@"Insert Into y_Mall_Payment(MInterID,FPayID,FPayAmount,FCutIntegral,FPayRealAmount,FCouponMoney,
                  FCouponID) values (@MInterID,@FPayID,@FPayAmount,@m_FCutIntegral,@FPayRealAmount,@FCouponMoney,@FCouponID)");
            int m_FCutIntegral = 0;
            ltpara.Add(new SqlParameter("@MInterID", KInterID));
            ltpara.Add(new SqlParameter("@FPayID", _model.FPayID));
            ltpara.Add(new SqlParameter("@m_FCutIntegral", _model.FCutIntegral));

            decimal m_FPayRealAmount;

            m_FPayRealAmount = (li_RealMoney - _model.FCouponMoney + _model.FShippingAmt);
            ltpara.Add(new SqlParameter("@FPayAmount", m_zero));//(付款金额-优惠券)+快递费
            ltpara.Add(new SqlParameter("@FPayRealAmount", m_zero));//(实收金额-优惠券)+快递费
            ltpara.Add(new SqlParameter("@FCouponMoney", m_zero));
            ltpara.Add(new SqlParameter("@FCouponID", m_zero));

            SqlArray.Add(strSql);
            ParaArray.Add(ltpara.ToArray());


            bool v = DBHelper.BatchExecuteBySql(SqlArray.ToArray(), ParaArray.ToArray(), DBHelper.ConnMaster);
            if (v)
            {
                strSql = new StringBuilder();
                strSql.AppendFormat("Exec pr_wap_SetMallBillData {0}", KInterID);
                DBHelper.ExeSQL(strSql.ToString(), DBHelper.ConnMaster);
                return true;
            }

            return false;
        }

        /// <summary>
        /// 获取优惠后的总金额
        /// </summary>
        /// <param name="weiXinId"></param>
        /// <param name="corpId"></param>
        /// <param name="importsFlag"></param>
        /// <returns></returns>
        public static decimal GetTotalAmount(string weiXinId, string corpId, string importsFlag)
        {
            StringBuilder strSql = new StringBuilder();
            List<SqlParameter> ltParams = new List<SqlParameter>();
            strSql.Append(@"exec pr_wap_GetTotalAmount @FWeixinID,@FCorpID,@FImportFlag");
            ltParams.Add(new SqlParameter("@FWeixinID", weiXinId));
            ltParams.Add(new SqlParameter("@FCorpID", corpId));
            ltParams.Add(new SqlParameter("@FImportFlag", importsFlag));
            DataTable dt = DBHelper.GetDataTable(strSql.ToString(), ltParams.ToArray(), DBHelper.ConnMaster);
            return Convert.ToDecimal(dt.Rows[0][0]);
        }

        public static long GetMaxAutoID(string strTablename, string strFieldname)
        {
            List<SqlParameter> ltPar = new List<SqlParameter>()
            {
                new SqlParameter("@strTablename",strTablename),
                new SqlParameter("@strFieldname",strFieldname),
            };
            Hashtable hs = DBHelper.Select(@"exec  pr_bi_GetMaxAutoIDEx @strTablename,@strFieldname", ltPar.ToArray(), DBHelper.ConnMaster)[0] as Hashtable;
            Int64? v = hs?["FLastID"] as Int64?;
            return v == null ? 1 : v.Value;
        }


        /// <summary>
        /// 获取订单收款数据
        /// </summary>
        /// <param name="weiXinId"></param>
        /// <param name="fCorpId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="model"></param>
        /// <param name="buy"></param>
        /// <returns></returns>
        public static DataTable Get_Order_Payment(long weiXinId, long fCorpId, int pageIndex, int pageSize, T_OrderList model, string buy = "")
        {
            string msql = "";
            if (model.StateID != -1)
            {
                msql += string.Format(" and c.FPayType = {0}", model.StateID > 0 ? "1" : "0");
            }
            if (model.StateID >= 0)
            {
                msql += string.Format(" and c.FStateID = {0}", model.StateID);
            }
            if (buy == "0")
            {
                msql += string.Format(" and c.FStateID <> {0}", buy);
            }
            if (model.GoodsID > 0)
            {
                msql += string.Format(" and a.MInterID in (select MInterID from y_Mall_Detail where mFGoodID = {0})", model.GoodsID);
            }
            if (!string.IsNullOrWhiteSpace(model.BgDate) && !string.IsNullOrWhiteSpace(model.EnDate))
            {
                msql += string.Format(" and LEFT(CONVERT(varchar(16),c.FDate,120),10) between '{0}' and '{1}'",
                    model.BgDate, model.EnDate);
            }
            if (model.FBillType >= 0)
            {
                msql += string.Format(" and c.FBillType = {0}", model.FBillType);
            }
            msql += "   and   FPaymentID = 7 ";

            List<SqlParameter> ht = new List<SqlParameter>() {
            new SqlParameter("@mPageSize",pageSize),
            new SqlParameter("@mPageIndex",pageIndex),
            new SqlParameter("@mWeiXinID",weiXinId),
            new SqlParameter("@mCorpID",fCorpId),
            new SqlParameter("@mConditon",msql),
            };

            return DBHelper.GetDataTable("pr_wap_GetOrderList @mPageSize ,@mPageIndex ,@mWeiXinID ,@mCorpID,@mConditon", ht.ToArray(), DBHelper.ConnMaster);
        }

    }
}
